<script lang="ts">
import { PropType, h, reactive } from 'vue'
import ADropdown from './ADropdown.vue'
import AControlGroup from './AControlGroup.vue'
import { PopPlacementType, TriggerType } from '@/types'

interface PropsType {
    displayCount: number
    popPlacement: PopPlacementType
    trigger: TriggerType
}
interface StateType {
    popShown: boolean
}

export default {
    props: {
        displayCount: {
            type: Number,
            default: 0,
        },
        popPlacement: {
            type: String as PropType<PopPlacementType>,
            default: 'bottom'
        },
        trigger: {
            type: String as PropType<TriggerType>,
            default: 'click'
        },
    },
    setup(props: PropsType, ctx) {
        const state = reactive<StateType>({
            popShown: false,
        })

        const methods = {
            hidePop() {
                state.popShown = false
            }
        }

        ctx.expose({
            hidePop: methods.hidePop,
        })

        return () => {
            let buttons = ctx.slots.default!()
            let displayButtons = buttons.slice(0, props.displayCount)
            let hideButtons = buttons.slice(props.displayCount, buttons.length)

            let displayButtonElList = displayButtons.map(a => h(a))
            let hideButtonElList = hideButtons.map(a => h(a))

            if (hideButtonElList.length) {
                let moreBtnEl = h(ADropdown,
                    {
                        popShown: state.popShown,
                        'onUpdate:popShown': (value: boolean) => state.popShown = value,
                        popPlacement: props.popPlacement,
                        trigger: props.trigger,
                    },
                    {
                        default: ctx.slots.moreBtn,
                        pop: () => h(AControlGroup, {
                            direction: 'v',
                        }, {
                            default: () => hideButtonElList
                        })
                    })
                displayButtonElList.push(moreBtnEl)
            }

            let displayGroupEl = h(AControlGroup, {}, {
                default: () => displayButtonElList
            })

            return displayGroupEl
        }
    }
}
</script>